import React, { useState } from 'react';
import { message } from 'antd';
import InvestmentPlanList, { SavedInvestmentPlan } from './components/InvestmentPlanList';
import InvestmentPlanForm from './components/InvestmentPlanForm';
import { fundInvestPlanService, SavedFundInvestPlan } from '../../services/investPlanService';
import { 
  FundInfo, 
  InvestmentConfig, 
  InvestmentPlan as BaseInvestmentPlan, 
  StrategyType
} from '../../types/investment';
import './index.less';

interface InvestmentPlan extends BaseInvestmentPlan {
  fundInfo: FundInfo;
}

type ViewMode = 'list' | 'create' | 'edit' | 'view';

const FundInvestmentPlan: React.FC = () => {
  const [viewMode, setViewMode] = useState<ViewMode>('list');
  const [editingPlan, setEditingPlan] = useState<SavedInvestmentPlan | null>(null);

  // 切换到新增模式
  const handleCreateNew = () => {
    setEditingPlan(null);
    setViewMode('create');
  };

  // 切换到编辑模式
  const handleEdit = (plan: SavedInvestmentPlan) => {
    setEditingPlan(plan);
    setViewMode('edit');
  };

  // 查看投资计划详情
  const handleView = (plan: SavedInvestmentPlan) => {
    setEditingPlan(plan);
    setViewMode('view');
  };

  // 返回列表
  const handleBack = () => {
    setViewMode('list');
    setEditingPlan(null);
  };

  // 保存投资计划
  const handleSave = async (plan: InvestmentPlan) => {
    try {
      const savedPlan: SavedFundInvestPlan = {
        id: editingPlan?.id || Date.now().toString(),
        fundCode: plan.fundInfo.code,
        fundName: plan.fundInfo.name,
        currentPrice: plan.fundInfo.currentPrice,
        maxDrawdown: plan.fundInfo.maxDrawdown,
        totalAmount: plan.totalInvestment,
        buyTimes: plan.buyPoints.length,
        strategy: getStrategyFromPlan(plan),
        averagePrice: plan.averagePrice,
        riskLevel: plan.riskAnalysis.riskLevel,
        maxLoss: plan.riskAnalysis.maxLoss,
        expectedShares: plan.expectedShares,
        
        // 基金特有字段 - 使用默认值或从计划中获取
        fundType: '混合型', // 默认值，后续可以从表单中获取
        fundCompany: '未知', // 默认值，后续可以从表单中获取
        managementFee: 1.5, // 默认管理费率
        custodyFee: 0.25, // 默认托管费率
        subscriptionFee: 1.2, // 默认申购费率
        redemptionFee: 0.5, // 默认赎回费率
        minInvestAmount: 1, // 默认最小投资金额
        
        createdAt: editingPlan?.createdAt || new Date().toISOString(),
        updatedAt: new Date().toISOString()
      };

      await fundInvestPlanService.saveFundInvestPlan(savedPlan);
      
      // 返回列表页面
      handleBack();
    } catch (error) {
      console.error('保存投资计划失败:', error);
      message.error('保存投资计划失败');
    }
  };

  // 从投资计划中推断策略类型
  const getStrategyFromPlan = (plan: InvestmentPlan): string => {
    // 这里可以根据买入点的分配模式来推断策略
    // 简化处理，返回默认策略
    return 'pyramid';
  };

  // 将保存的计划转换为表单初始值
  const getInitialFormData = (plan: SavedInvestmentPlan) => {
    return {
      code: plan.fundCode,
      name: plan.fundName,
      currentPrice: plan.currentPrice,
      maxDrawdown: plan.maxDrawdown || -30, // 从保存的数据中获取，如果没有则使用默认值
      totalAmount: plan.totalAmount,
      buyTimes: plan.buyTimes,
      strategy: plan.strategy as StrategyType
    };
  };

  // 根据当前模式渲染不同的组件
  const renderContent = () => {
    switch (viewMode) {
      case 'create':
        return (
          <InvestmentPlanForm
            onBack={handleBack}
            onSave={handleSave}
            mode="create"
          />
        );
      case 'edit':
        return (
          <InvestmentPlanForm
            onBack={handleBack}
            onSave={handleSave}
            initialData={editingPlan ? getInitialFormData(editingPlan) : undefined}
            mode="edit"
          />
        );
      case 'view':
        return (
          <InvestmentPlanForm
            onBack={handleBack}
            onSave={handleSave}
            initialData={editingPlan ? getInitialFormData(editingPlan) : undefined}
            mode="view"
          />
        );
      default:
        return (
          <InvestmentPlanList
            onCreateNew={handleCreateNew}
            onEdit={handleEdit}
            onView={handleView}
          />
        );
    }
  };

  return (
    <div className="fund-investment-plan">
      {renderContent()}
    </div>
  );
};

export default FundInvestmentPlan;